package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.model.MaoYanAccountBoxModel;
import com.xiaotu.common.model.MaoYanScoreSupplement;
import com.xiaotu.common.util.CacheHandler;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.common.util.HtmlUtil;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.common.util.PropertiesUtil;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.SepratorUtil;
import com.xiaotu.spider.APageProcessor;

import net.sf.json.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.selector.Html;

@Component("MaoYanAccountBoxPageProcessor")
public class MaoYanAccountBoxPageProcessor extends APageProcessor {
	
	@Autowired
	private CacheHandler cacheHandler;
	
	private Map<String,String> cookies = new HashMap<String,String>();
	
	{ 
		cookies.put("Cookie", PropertiesUtil.getProperty("BoxOffice.site.Cookie"));
	}
	
	
	public static final String BASEINFO_URL = "http://piaofang.maoyan.com/movie/%s";//基础信息
	
	
	@SuppressWarnings("unchecked")
	@Override
	protected Request getStartRequest(JSONObject target) {
		Request request = new Request(String.format(BASEINFO_URL, target.getString("dataid")));
		request.setExtras((Map<String, Object>)target);
		return request;
	}
	
	@Override
	public void process(Page page) {
		
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		
		switch (this.getPageDataType(page))
        {
           
            case Constants.PageDataType.BASICINFO:
                this.basicinfoProcess(page,extrasMap);
                break;	
        }
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("http://piaofang.maoyan.com/movie")){
        	return Constants.PageDataType.BASICINFO;
        }
        return null;
	}
	
	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}
	
	
	private void basicinfoProcess(Page page, Map<String, Object> extraMap) {
		
		String url = page.getRequest().getUrl();
		
		String dataId = extraMap.get("dataid").toString();
		
		String tvName = extraMap.get("tvname").toString();
		Html html = null;
		
		if(url.contains(dataId)){
			//解密数据
			try {
				
				html = PageUtils.spiderAudienceRating(page,cookies);
				
			} catch (Exception e) {
				System.exit(0);
			}
	        
	        //评分相关
	        String score = "";
	        String starLevel = "";
	        String cinemaScore = "";//观众评分人数
	        String wantToSee = "";//想看人数
	        String imdbScore = "";//imdb评分
	        
	        //票房相关
	        String totalBoxoffice = null;// 累计票房
	        String firstDayBoxoffice = null;// 首日票房
	        String firstWeekBoxoffice = null;// 首周票房
	        String forecastBoxoffice = null;// 预测票房
	        String boxoffice = null; // 分账总票房
	        String productionBox = null;//片方票房
	        String cinemaBox = null;//影院票房
	        String otherBox = null;//其他票房
	        
	        List<String> checkDataList = new ArrayList<String>();
	        
			try {
				
	        	List<String> starLevelList = new ArrayList<String>();
	        	List<String> ratingStarsDivList = html.xpath("//div[@class='rating-stars']").all();
	        	if(ratingStarsDivList.size()>0){
	        		List<String> starsList = new Html(ratingStarsDivList.get(0)).xpath("//div[@class='rating-stars']//span").all();
	        		//是否存在评分数据
	                if(starsList.size()==6){
	                	for(int i = 0;i<starsList.size();i++ ){
	                    	Html starHtml = new Html(starsList.get(i));
	                    	if(starHtml.xpath("//span//@class").get().equals("rating-num")){
	                    		score = HtmlUtil.delHTMLTag(starHtml.xpath("//span").get());
	                    	}else{
	                    		starLevelList.add(HtmlUtil.delHTMLTag(starHtml.xpath("//span//@class").get()));
	                    	}
	                    }
	                }
	        	}
	            
	            if(starLevelList.size() == 5){
	            	starLevel = getStarLevel(starLevelList);
	            }
	            
	            cinemaScore = html.xpath("//div[@class='score-detail']//p[@class='detail-score-count']//text()").get();
	            if(StringUtils.isNotBlank(cinemaScore)){
	            	cinemaScore = cinemaScore.replace("观众评分","").trim();
	            }
	            wantToSee = html.xpath("//div[@class='score-detail']//p[@class='detail-wish-count']//text()").get();
	            if(StringUtils.isBlank(wantToSee)){//重新获取
	            	wantToSee = html.xpath("//div[@class='block-wish-item left']//h2//text()").get();
	            	if(wantToSee.contains("暂无想看")){
	            		wantToSee = null;
	            	}
	            }
	            if(StringUtils.isNotBlank(wantToSee)){
	            	wantToSee = wantToSee.replace("人想看","").trim();
	            }
	            String otherScoreStr = html.xpath("//div[@class='score-detail']//p[@class='detail-other-score']//text()").get();
	            if(null != otherScoreStr){
	            	String [] otherScoreArr = otherScoreStr.replace("其他评分 : ","").split(" ");
	            	imdbScore = otherScoreArr[1];
	            }
	            
			} catch (Exception e) {
				System.out.println("评分异常信息当前数据id:"+dataId+"电影名称:"+tvName+"-----------"+MaoYanMovieRelatedDataPageProcessor.class.getName()+" detailProcess() ");
			}
			try {
				
				if(imdbScore.equals("")) {
					String otherScoreStr = html.xpath("//div[@class='score-detail']//p[@class='detail-other-score']//text()").get();
		            if(null != otherScoreStr){
		            	String [] otherScoreArr = otherScoreStr.replace("其他评分 : ","").split(" ");
		            	imdbScore = otherScoreArr[1];
		            }
				}
				
			} catch (Exception e) {
				
			}
			
			
			try {
				
	            //累计票房相关
	            checkDataList = html.xpath
	            		("//div[@class='movie-container']//div[@class='info-detail-row']").all();
	            if (checkDataList.size()>0){
	            	String boxOfficeLine =html.xpath
		            		("//div[@class='movie-container']//div[@class='info-detail-row']").all().get(0);
		            Html htmlUp = new Html(boxOfficeLine);
		            List<String> allUp = htmlUp.xpath("//div[@class='info-detail-row']//div").all();
		            if(new Html(allUp.get(0)).xpath("//p[@class='info-detail-title']").get().trim().contains("累计票房")){
		            	totalBoxoffice = getFormattedData(new Html(allUp.get(0)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
		            }
		            if(new Html(allUp.get(2)).xpath("//p[@class='info-detail-title']").get().trim().contains("首日票房")){
		            	firstDayBoxoffice = getFormattedData(new Html(allUp.get(2)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
		            }
		            if(new Html(allUp.get(4)).xpath("//p[@class='info-detail-title']").get().trim().contains("首周票房")){
		            	firstWeekBoxoffice = getFormattedData(new Html(allUp.get(4)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
		            }
		            if(new Html(allUp.get(6)).xpath("//p[@class='info-detail-title']").get().trim().contains("预测票房")){
		            	forecastBoxoffice = getFormattedData(new Html(allUp.get(6)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
		            }
		            
		            
		            //分账票房相关
		            String boxOffice =html.xpath
		            		("//div[@class='movie-container']//div[@class='info-detail-row']").all().get(1);
		            Html htmls = new Html(boxOffice);
		            List<String> all = htmls.xpath("//div[@class='info-detail-row']//div").all();
		            if (all != null && all.size() == 8){
		            	if(new Html(all.get(0)).xpath("//p[@class='info-detail-title']").get().trim().contains("分账票房")){
			            	boxoffice = getFormattedData(new Html(all.get(0)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", ""); 
			            }
			            if(new Html(all.get(3)).xpath("//p[@class='info-detail-title']").get().trim().contains("片方")){
			            	productionBox = getFormattedData(new Html(all.get(3)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
			            }
			            if(new Html(all.get(5)).xpath("//p[@class='info-detail-title']").get().trim().contains("影院")){
			            	cinemaBox = getFormattedData(new Html(all.get(5)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
			            }
			            if(new Html(all.get(7)).xpath("//p[@class='info-detail-title']").get().trim().contains("其他")){
			            	otherBox = getFormattedData(new Html(all.get(7)).xpath("//p[@class='info-detail-content']").get()).replace("--", "").replace("暂无", "");
			            }
		            }
	            }
	            
			} catch (Exception e) {
				System.out.println("票房异常信息 ERROR   basicinfoProcess()当前异常信息...........当前url链接为："+url);
			}
			
			MaoYanAccountBoxModel maoYanSearchMovieModel = new MaoYanAccountBoxModel
					(dataId, tvName, totalBoxoffice, firstDayBoxoffice, firstWeekBoxoffice, 
							forecastBoxoffice, boxoffice, productionBox, cinemaBox, otherBox);
			
//			if(score!="" || starLevel !="" || cinemaScore!="" || wantToSee!="" || imdbScore!="") {
//				MaoYanScoreSupplement obj = new MaoYanScoreSupplement(
//                		dataId,
//                		tvName,
//                		score,
//                		starLevel,
//                		cinemaScore,
//                		wantToSee,
//                		imdbScore
//                		);
//            	String key = "SCORE_SUPPLEMENT";
//            	cacheHandler.hSet(key, obj.getDataid()+"_"+obj.getTvname(), obj);
//            	
//            }
			
			if (totalBoxoffice!=null){
				page.putField(MaoYanAccountBoxModel.class.getName(), maoYanSearchMovieModel);
			}
			//cacheHandler.hSet("MAOYAN_SEARCH_MOVIE_NEW", extraMap.get("dataid").toString()+"_"+tvName, extraMap);
			cacheHandler.hDel("ERROR_INFO", extraMap.get("dataid").toString()+"_"+tvName);
		}
		
	}
	
	private String getFormattedData(String data){
        return RegexUtils.replaceStr(HtmlUtil.delHTMLTag(data), SepratorUtil.SEP_SPACE_EN,
                StringUtils.EMPTY);
    }
	
	@SuppressWarnings({ "unused"})
	private String getStarLevel(List<String> list){
		Double starLevel = 0.0;
		if(list == null || list.size()<0)
		return null;
		for(String str: list){
			if(str.contains("fullstar")){
				starLevel +=1; 
			}else if(str.contains("halfstar")){
				starLevel+=0.5;
			}
		}
		return starLevel+"";
	}
	
	private String[] matchShowingAreaAndShowingDate(String str){
			
			String[] data = new String[2];
			if(StringUtils.isNotBlank(str)){
				if(regexStr("[\u4e00-\u9fa5-:]",str).length()>=8){
					data[0] = regexStr("[\u4e00-\u9fa5]",str);
					data[1] = regexStr("[0-9:-]",str);
				}else if (StringUtils.isEmpty(regexStr("[\u4e00-\u9fa5]",str))){
					data[1] = str.trim();
					data[0] = null;
				}else if (StringUtils.isEmpty(regexStr("[0-9:-]",str))){
					data[0] = str.trim();
					data[1] = null;
				}
			}
			
			return data;
	}
	
	private String regexStr(String regex,String str){
		
		String reg = regex;

		Pattern pat = Pattern.compile(reg);  

		Matcher mat=pat.matcher(str); 

		String returnStr = mat.replaceAll("");
		
		return returnStr;
	}
	
	private String convertDateStr(String str){
    	String first = str.substring(0,4);
    	String second = str.substring(4, 6);
    	String three = str.substring(6);
    	return first+"-"+second+"-"+three;
    }
	
}
